package com.risetechnology.krystalkitchen1;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.risetechnology.common.Const;
import com.risetechnology.common.Shared;
import com.risetechnology.data.Recipe;
import com.risetechnology.data.Schedule;
import com.risetechnology.master.NavigationActivity;
import com.risetechnology.services.AlertService;

public class ActivityOrganiseSchedule extends NavigationActivity {

	private EditText etTitle;
	private TextView etTimeOfMeal;
	private TextView etReminder;
	private TextView edtEntree;
	private TextView edtMain;
	private TextView edtDessert;
	private TextView edtDrinks;

	private String dayOfMonth;
	private String month;
	private String year;
	private String entree, main, desert, drink;

	private static final int SERVING_TIME_DIALOG_ID = 1001;
	private static final int PREPARE_TIME_DIALOG_ID = 1002;
	private int hour;
	private int minute;
	private long reminderTime = 0;
	private ArrayList<Recipe> sEntrees, sMains, sDesserts, sDrinks;
	private ArrayList<Recipe> rEntrees, rMains, rDesserts, rDrinks;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_organise_schedule);

		// Set contents
		setContents();
	}

	private void setContents() {
		dayOfMonth = getIntent().getStringExtra(Const.KEY_DAY_OF_MONTH);
		month = getIntent().getStringExtra(Const.KEY_MONTH);
		year = getIntent().getStringExtra(Const.KEY_YEAR);

		etTitle = (EditText) findViewById(R.id.et_title);
		etTitle.setTypeface(Shared.font);

		etTimeOfMeal = (TextView) findViewById(R.id.tv_time_of_meal);
		etTimeOfMeal.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v) {
				showDialog(SERVING_TIME_DIALOG_ID);
			}
		});
		etTimeOfMeal.setTypeface(Shared.font);

		etReminder = (TextView) findViewById(R.id.tv_reminder_at);
		etReminder.setOnClickListener(new OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v) {
				showDialog(PREPARE_TIME_DIALOG_ID);
			}
		});
		etReminder.setTypeface(Shared.font);

		entree = "";
		main = "";
		desert = "";
		drink = "";

		rEntrees = Shared.dbAdapter.getRecipeByMeal2(0, null);
		rMains = Shared.dbAdapter.getRecipeByMeal2(1, null);
		rDesserts = Shared.dbAdapter.getRecipeByMeal2(2, null);
		rDrinks = Shared.dbAdapter.getRecipeByMeal2(3, null);

		sEntrees = new ArrayList<Recipe>();
		sMains = new ArrayList<Recipe>();
		sDesserts = new ArrayList<Recipe>();
		sDrinks = new ArrayList<Recipe>();

		edtEntree = (TextView) findViewById(R.id.edt_entree);
		edtDessert = (TextView) findViewById(R.id.edt_dessert);
		edtMain = (TextView) findViewById(R.id.edt_main);
		edtDrinks = (TextView) findViewById(R.id.edt_drinks);
		showDesserts();
		showDrinks();
		showEntrees();
		showMains();

		edtEntree.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (rEntrees != null && rEntrees.size() > 0)
					new ChooseRecipeDialog(ActivityOrganiseSchedule.this
							.getParent(), rEntrees, sEntrees,
							new ChooseRecipeDialog.SelectedListener() {

								@Override
								public void onSelected(
										ArrayList<Recipe> choosenRecipe) {
									sEntrees = choosenRecipe;
									showEntrees();
								}
							}).show();
			}
		});
		edtDessert.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (rDesserts != null && rDesserts.size() > 0)
					new ChooseRecipeDialog(ActivityOrganiseSchedule.this
							.getParent(), rDesserts, sDesserts,
							new ChooseRecipeDialog.SelectedListener() {

								@Override
								public void onSelected(
										ArrayList<Recipe> choosenRecipe) {
									sDesserts = choosenRecipe;
									showDesserts();
								}
							}).show();
			}
		});
		edtMain.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (rMains != null && rMains.size() > 0)
					new ChooseRecipeDialog(ActivityOrganiseSchedule.this
							.getParent(), rMains, sMains,
							new ChooseRecipeDialog.SelectedListener() {

								@Override
								public void onSelected(
										ArrayList<Recipe> choosenRecipe) {
									sMains = choosenRecipe;
									showMains();
								}
							}).show();
			}
		});
		edtDrinks.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (rDrinks != null && rDrinks.size() > 0)
					new ChooseRecipeDialog(ActivityOrganiseSchedule.this
							.getParent(), rDrinks, sDrinks,
							new ChooseRecipeDialog.SelectedListener() {

								@Override
								public void onSelected(
										ArrayList<Recipe> choosenRecipe) {
									sDrinks = choosenRecipe;
									showDrinks();
								}
							}).show();
			}
		});

		LinearLayout llSet = (LinearLayout) findViewById(R.id.ll_set);
		llSet.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String title = etTitle.getText().toString();
				String preTime = etReminder.getText().toString();
				String serTime = etTimeOfMeal.getText().toString();

				if(!validateForm(title, preTime, serTime)){
					return;
				}
				
				Schedule schedule = new Schedule(-1, title, preTime, serTime,
						dayOfMonth, month, year, entree, main, desert, drink,
						reminderTime);

				StringBuilder temp = new StringBuilder();
				int i = 0;
				if (sEntrees.size() > 0) {
					for (; i < sEntrees.size() - 1; i++) {
						temp.append(sEntrees.get(i).getId());
						temp.append(" ");
					}
					temp.append(sEntrees.get(i).getId());
				}
				schedule.setEntree(temp.toString());
				temp = new StringBuilder();
				i = 0;
				if (sDesserts.size() > 0) {
					for (; i < sDesserts.size() - 1; i++) {
						temp.append(sDesserts.get(i).getId());
						temp.append(" ");
					}
					temp.append(sDesserts.get(i).getId());
				}
				schedule.setDessert(temp.toString());
				temp = new StringBuilder();
				i = 0;
				if (sMains.size() > 0) {
					for (; i < sMains.size() - 1; i++) {
						temp.append(sMains.get(i).getId());
						temp.append(" ");
					}
					temp.append(sMains.get(i).getId());
				}
				schedule.setMain(temp.toString());
				temp = new StringBuilder();
				i = 0;
				if (sDrinks.size() > 0) {
					for (; i < sDrinks.size() - 1; i++) {
						temp.append(sDrinks.get(i).getId());
						temp.append(" ");
					}
					temp.append(sDrinks.get(i).getId());
				}
				schedule.setDrinks(temp.toString());

				int id = (int)Shared.dbAdapter.addSchedule(schedule);
				
				for (i = 0; i < sEntrees.size(); i++) {
					Shared.dbAdapter.addScheduleRecipe(id, sEntrees
							.get(i).getId());
				}

				for (i = 0; i < sMains.size(); i++) {
					Shared.dbAdapter.addScheduleRecipe(id, sMains
							.get(i).getId());
				}

				for (i = 0; i < sDrinks.size(); i++) {
					Shared.dbAdapter.addScheduleRecipe(id, sDrinks
							.get(i).getId());
				}

				for (i = 0; i < sDesserts.size(); i++) {
					Shared.dbAdapter.addScheduleRecipe(id, sDesserts
							.get(i).getId());
				}

				setAlarmReminder(title, preTime, id);

				ActivityDaySchedule.getSchedules(dayOfMonth, month, year);
				ActivityCalendar.refreshCalendar();
				onBackPressed();
			}
		});

		LinearLayout llCancel = (LinearLayout) findViewById(R.id.ll_cancel);
		llCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				onBackPressed();
			}
		});

		TextView textviewTitle = (TextView) findViewById(R.id.tv_title);
		textviewTitle.setTypeface(Shared.font);

		TextView textviewSet = (TextView) findViewById(R.id.tv_set);
		textviewSet.setTypeface(Shared.font);

		TextView textviewCancel = (TextView) findViewById(R.id.tv_cancel);
		textviewCancel.setTypeface(Shared.font);
	}

	public void showEntrees() {
		if (rEntrees == null || rEntrees.size() == 0) {
			entree = "No recipe available";
		} else if (sEntrees.size() == 0) {
			entree = "Select recipe";
		} else {
			entree = "";
			for (Recipe recipe : sEntrees) {
				if (entree.length() == 0)
					entree += recipe.getName();
				else {
					entree += ", " + recipe.getName();
				}
			}
		}
		edtEntree.setText(entree);
	}

	public void showDesserts() {
		if (rDesserts == null || rDesserts.size() == 0) {
			desert = "No recipe available";
		} else if (sDesserts.size() == 0) {
			desert = "Select recipe";
		} else {
			desert = "";
			for (Recipe recipe : sDesserts) {
				if (desert.length() == 0) {
					desert += recipe.getName();
				} else {
					desert += ", " + recipe.getName();
				}
			}
		}
		edtDessert.setText(desert);
	}

	public void showMains() {
		if (rMains == null || rMains.size() == 0) {
			main = "No recipe available";
		} else if (sMains.size() == 0) {
			main = "Select recipe";
		} else {
			main = "";
			for (Recipe recipe : sMains) {
				if (main.length() == 0) {
					main += recipe.getName();
				} else {
					main += ", " + recipe.getName();
				}
			}
		}
		edtMain.setText(main);

	}

	public void showDrinks() {
		if (rDrinks == null || rDrinks.size() == 0) {
			drink = "No recipe available";
		} else if (sDrinks.size() == 0) {
			drink = "Select recipe";
		} else {
			drink = "";
			for (Recipe recipe : sDrinks) {
				if (drink.length() == 0) {
					drink += recipe.getName();
				} else {
					drink += "," + recipe.getName();
				}
			}
		}
		edtDrinks.setText(drink);
	}

	private void setAlarmReminder(String name, String time, long id) {
		Intent myIntent = new Intent(this, AlertService.class);
		myIntent.putExtra("SCHEDULE_NAME", name);
		myIntent.putExtra("SCHEDULE_TIME", time);

		PendingIntent pendingIntent = PendingIntent.getService(this, (int) id,
				myIntent, 0);

		AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

		alarmManager.set(AlarmManager.RTC_WAKEUP, reminderTime, pendingIntent);
	}

	private boolean validateForm(String title, String preTime, String serTime) {
		if (title == null || title.length() == 0) {
			Toast.makeText(ActivityOrganiseSchedule.this.getParent(),
					"Please input title", Toast.LENGTH_LONG).show();
			return false;
		} else if (serTime == null || serTime.length() == 0) {
			Toast.makeText(ActivityOrganiseSchedule.this.getParent(),
					"Please input serve time", Toast.LENGTH_LONG).show();
			return false;
		} else if (preTime == null || preTime.length() == 0) {
			Toast.makeText(ActivityOrganiseSchedule.this.getParent(),
					"Please input prepare time", Toast.LENGTH_LONG).show();
			return false;
		}

		return true;
	}

	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		switch (id) {
		case SERVING_TIME_DIALOG_ID:
			// set time picker as current time
			return new TimePickerDialog(this.getParent(),
					servingTimePickerListener, c.get(Calendar.HOUR_OF_DAY),
					c.get(Calendar.MINUTE), false);
		case PREPARE_TIME_DIALOG_ID:
			// set time picker as current time
			return new TimePickerDialog(this.getParent(),
					prepareTimePickerListener, c.get(Calendar.HOUR_OF_DAY),
					c.get(Calendar.MINUTE), false);
		}
		return null;
	}

	private TimePickerDialog.OnTimeSetListener servingTimePickerListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			hour = selectedHour;
			minute = selectedMinute;

			String ampm = "AM";

			Calendar datetime = Calendar.getInstance();
			datetime.set(Calendar.HOUR_OF_DAY, hour);
			datetime.set(Calendar.MINUTE, minute);

			if (datetime.get(Calendar.AM_PM) == Calendar.AM) {
				ampm = "AM";
			} else if (datetime.get(Calendar.AM_PM) == Calendar.PM) {
				ampm = "PM";
				if (hour > 12) {
					hour = hour - 12;
				}
			}

			etTimeOfMeal.setText(new StringBuilder().append(paddingTime(hour))
					.append(":").append(paddingTime(minute)).append(ampm));
		}
	};

	@SuppressLint("SimpleDateFormat")
	private TimePickerDialog.OnTimeSetListener prepareTimePickerListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour,
				int selectedMinute) {
			hour = selectedHour;
			minute = selectedMinute;

			Calendar select = Calendar.getInstance();
			String date = dayOfMonth + " " + month + " " + year;
			try {
				Date d = new SimpleDateFormat("dd MMM yyyy").parse(date);
				select.setTime(d);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			select.set(Calendar.HOUR_OF_DAY, selectedHour);
			select.set(Calendar.MINUTE, selectedMinute);
			select.set(Calendar.SECOND, 0);

			if (select.getTimeInMillis() <= Calendar.getInstance()
					.getTimeInMillis()) {
				Toast.makeText(getBaseContext(), "Invalid time!",
						Toast.LENGTH_SHORT).show();
				return;
			}

			String ampm = "AM";

			if (select.get(Calendar.AM_PM) == Calendar.AM) {
				ampm = "AM";
			} else if (select.get(Calendar.AM_PM) == Calendar.PM) {
				ampm = "PM";
				if (hour > 12) {
					hour = hour - 12;
				}
			}

			etReminder.setText(new StringBuilder().append(paddingTime(hour))
					.append(":").append(paddingTime(minute)).append(ampm));

			reminderTime = select.getTimeInMillis();
		}
	};

	private static String paddingTime(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}
}
